package code

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"time"
)

func Context01() {
	// 三个请求一共需要5秒
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	// 调用cancel后, 把所有请求终止
	defer cancel()
	urls := []string{
		"http://127.0.0.1/users",
		"http://127.0.0.1/products",
		"http://127.0.0.1/orders",
	}
	results := make(chan string)
	for _, url := range urls {
		go func(url string) {
			fetchAPI(ctx, url, results)
		}(url)
	}

	for range urls {
		fmt.Println(<-results)
	}
}

func fetchAPI(ctx context.Context, url string, results chan string) {
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
	if err != nil {
		results <- fmt.Sprintf("Error creating request: %v, error:%v", url, err)
		return
	}
	client := http.DefaultClient
	response, err := client.Do(req)
	if err != nil {
		results <- fmt.Sprintf("Error fetching API: %v, error:%v", url, err)
		return
	}
	defer response.Body.Close()

	buff := make([]byte, 1024)
	for {
		n, err := response.Body.Read(buff)
		if err != nil && err.Error() != "EOF" {
			log.Fatal(err)
		} else {
			fmt.Printf("string(buff[:n]): %v\n", string(buff[:n]))
			break
		}
	}
	results <- fmt.Sprintf("Successfully fetched API: %v, statusCode: %v", url, response.StatusCode)

}
